# -*- coding: utf-8 -*-
class envHelper(object):
    _userAgent = ''
    Browser = {'name':'unknown','version':'unknown'} 
    OS = {'name':'unknown'}
    _browserLib = [
                {'name':'Tencent Traveler','key':'TencentTraveler','vkey':'TencentTraveler'},
                {'name':'Netscape','key':'Netscape','vkey':'Netscape'},{'name':'Chrome','key':'Chrome','vkey':'Chrome\/'},
                {'name':'MSIE','key':'MSIE','vkey':'MSIE'},{'name':'Firefox','key':'Firefox','vkey':'Firefox\/'},
                {'name':'Opera','key':'Opera','vkey':'Version\/'},{'name':'Safari','key':'Safari','vkey':'Version\/'}
                ]
    _osLib = [
            {'name':'Windows CE','key':'Windows CE'}, {'name':'blackberry','key':'blackberry'},
            {'name':'android','key':'android'},
            {'name':'iPad','key':'iPad'},{'name':'iPhone','key':'iPhone'},{'name':'iPod','key':'iPod'},
            {'name':'palm','key':'palm'},{'name':'Windows 98','key':'Windows 98'},
            {'name':'Windows NT4.0','key':'Windows NT 4.0'}, {'name':'Windows 2000','key':'Windows NT 5.0'},
            {'name':'Windows XP','key':'Windows NT 5.1'}, {'name':'Windows 2003','key':'Windows NT 5.2'},
            {'name':'Windows Vista','key':'Windows NT 6.0'},{'name':'Windows 7','key':'Windows NT 6.1'},
            {'name':'Ubuntu','key':'Ubuntu'},{'name':'Linux','key':'Linux'}, {'name':'Mac','key':'Mac'}
            ]
    def __init__(self,userAgent):
        self._userAgent = userAgent;
        self.getBrowser(self._userAgent)
        self.getOS(self._userAgent)
    def getBrowser(self,agent):
        import re
        agent = agent.lower()
        for i in range(len(self._browserLib)):
            item = self._browserLib[i]
            if agent.find(item['key'].lower()) >= 0:
                self.Browser['name'] = item['name'];
                # got browser, getting version now
                reg = re.compile('.*%s\\W*([.\\w]+)\\W*.*' % item['vkey'],re.I);
                version = reg.sub('\\1',agent); # agent.replace(reg,'\1');
                if version: self.Browser['version'] = version
                break;
    def getOS(self,agent):
        import re
        agent = agent.lower()
        for i in range(len(self._osLib)):
            item = self._osLib[i];
            if agent.find(item['key'].lower()) >= 0:
                self.OS['name'] = item['name']; break;
    
if __name__ == '__main__':
    agent = 'Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.10'
    env = envGetter(agent)
    print agent
    print env.Browser
    print env.OS
    print 'done'